package com.rocket.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;

public class FileUtils {

	public static String saveImage(Bitmap bitmap, String path) {
		File f = new File(path);
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return saveImage(f, bitmap);
	}

	public static String saveImage(File imageFile, Bitmap bitmapImage) {
		if (imageFile != null && bitmapImage != null) {
			CompressFormat format = null;
			if (imageFile.getName().toLowerCase().endsWith(".png")) {
				format = CompressFormat.PNG;
			} else if (imageFile.getName().toLowerCase().endsWith(".jpg")) {
				format = CompressFormat.JPEG;
			}

			if (imageFile.exists()) {
				imageFile.delete();
			}

			if (format != null) {
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				bitmapImage.compress(format, 100, os);
				return save(imageFile, os.toByteArray());
			}
			return "";
		}
		return "";
	}

	public static String save(File file, byte[] data) {
		try {
			OutputStream os = openOutputStream(file);
			os.write(data, 0, data.length);
			os.close();
			return file.getAbsolutePath();
		} catch (Exception e) {
			return "";
		}
	}

	public static FileOutputStream openOutputStream(File file)
			throws IOException {
		if (file.exists()) {
			if (file.isDirectory()) {
				throw new IOException("File '" + file
						+ "' exists but is a directory");
			}
			if (file.canWrite() == false) {
				throw new IOException("File '" + file
						+ "' cannot be written to");
			}
		} else {
			File parent = file.getParentFile();
			if (parent != null && parent.exists() == false) {
				if (parent.mkdirs() == false) {
					throw new IOException("File '" + file
							+ "' could not be created");
				}
			}
		}
		return new FileOutputStream(file);
	}

}
